import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useTranslation } from 'react-i18next'
import {
  ArrowLeftIcon,
  InformationCircleIcon,
  TagIcon,
  LinkIcon
} from '@heroicons/react/24/outline'
import { Card, Button, Input } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

const createPluginSchema = z.object({
  name: z.string()
    .min(1, 'Plugin name is required')
    .max(100, 'Plugin name must be less than 100 characters')
    .regex(/^[a-z0-9-]+$/, 'Plugin name can only contain lowercase letters, numbers, and hyphens'),
  displayName: z.string()
    .min(1, 'Display name is required')
    .max(100, 'Display name must be less than 100 characters'),
  description: z.string()
    .max(500, 'Description must be less than 500 characters')
    .optional(),
  category: z.string()
    .min(1, 'Category is required'),
  repositoryUrl: z.string()
    .url('Must be a valid URL')
    .optional()
    .or(z.literal('')),
  homepageUrl: z.string()
    .url('Must be a valid URL')
    .optional()
    .or(z.literal('')),
  documentationUrl: z.string()
    .url('Must be a valid URL')
    .optional()
    .or(z.literal('')),
  license: z.string()
    .max(50, 'License must be less than 50 characters')
    .optional(),
  keywords: z.string()
    .optional(),
  tags: z.string()
    .optional()
})

type CreatePluginFormData = z.infer<typeof createPluginSchema>

const categories = [
  { value: 'development', label: 'Development Tools' },
  { value: 'productivity', label: 'Productivity' },
  { value: 'utilities', label: 'Utilities' },
  { value: 'entertainment', label: 'Entertainment' },
  { value: 'education', label: 'Education' },
  { value: 'business', label: 'Business' },
  { value: 'graphics', label: 'Graphics & Design' },
  { value: 'communication', label: 'Communication' },
  { value: 'security', label: 'Security' },
  { value: 'other', label: 'Other' }
]

export const CreatePluginPage: React.FC = () => {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const [isSubmitting, setIsSubmitting] = useState(false)

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm<CreatePluginFormData>({
    resolver: zodResolver(createPluginSchema)
  })

  const pluginName = watch('name')

  const onSubmit = async (data: CreatePluginFormData) => {
    setIsSubmitting(true)
    try {
      // Process keywords and tags
      const processedData = {
        ...data,
        keywords: data.keywords ? data.keywords.split(',').map(k => k.trim()).filter(Boolean) : [],
        tags: data.tags ? data.tags.split(',').map(t => t.trim()).filter(Boolean) : []
      }

      // TODO: Implement API call to create plugin
      console.log('Creating plugin:', processedData)

      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000))

      // Navigate to plugin list or detail page
      navigate('/developer/plugins')
    } catch (error) {
      console.error('Failed to create plugin:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <ErrorBoundary>
      <div className="max-w-4xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex items-center space-x-4">
          <Button
            variant="ghost"
            onClick={() => navigate('/developer/plugins')}
            icon={<ArrowLeftIcon />}
          >
            {t('plugins.backToPlugins')}
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{t('plugins.createNew')}</h1>
            <p className="text-gray-600 mt-1">
              {t('plugins.createDescription')}
            </p>
          </div>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          {/* Basic Information */}
          <Card className="p-6">
            <Card.Header>
              <Card.Title>{t('plugins.form.basicInformation')}</Card.Title>
              <Card.Description>
                {t('plugins.form.basicInformationDescription')}
              </Card.Description>
            </Card.Header>
            <Card.Content>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="md:col-span-2">
                  <Input
                    label={t('plugins.form.name')}
                    placeholder="my-awesome-plugin"
                    helperText={t('plugins.form.nameHelper')}
                    error={errors.name?.message}
                    {...register('name')}
                  />
                  {pluginName && (
                    <div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded-md">
                      <p className="text-sm text-blue-800">
                        <InformationCircleIcon className="inline h-4 w-4 mr-1" />
                        {t('plugins.form.pluginAvailableAs')}: <code className="font-mono">@{pluginName}</code>
                      </p>
                    </div>
                  )}
                </div>

                <div className="md:col-span-2">
                  <Input
                    label={t('plugins.form.displayName')}
                    placeholder={t('plugins.form.displayNamePlaceholder')}
                    helperText={t('plugins.form.displayNameHelper')}
                    error={errors.displayName?.message}
                    {...register('displayName')}
                  />
                </div>

                <div className="md:col-span-2">
                  <label className="form-label">{t('plugins.form.description')}</label>
                  <textarea
                    className="form-textarea"
                    rows={3}
                    placeholder={t('plugins.form.descriptionPlaceholder')}
                    {...register('description')}
                  />
                  {errors.description && (
                    <p className="form-error">{errors.description.message}</p>
                  )}
                </div>

                <div>
                  <label className="form-label">{t('plugins.form.category')}</label>
                  <select
                    className="form-select"
                    {...register('category')}
                  >
                    <option value="">{t('plugins.form.selectCategory')}</option>
                    {categories.map(category => (
                      <option key={category.value} value={category.value}>
                        {t(`plugins.categories.${category.value}`, category.label)}
                      </option>
                    ))}
                  </select>
                  {errors.category && (
                    <p className="form-error">{errors.category.message}</p>
                  )}
                </div>

                <div>
                  <Input
                    label={t('plugins.form.license')}
                    placeholder="MIT, Apache-2.0, etc."
                    helperText={t('plugins.form.licenseHelper')}
                    error={errors.license?.message}
                    {...register('license')}
                  />
                </div>
              </div>
            </Card.Content>
          </Card>

          {/* URLs and Links */}
          <Card className="p-6">
            <Card.Header>
              <Card.Title>{t('plugins.form.linksResources')}</Card.Title>
              <Card.Description>
                {t('plugins.form.linksResourcesDescription')}
              </Card.Description>
            </Card.Header>
            <Card.Content>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Input
                    label={t('plugins.form.repositoryUrl')}
                    placeholder="https://github.com/username/plugin"
                    helperText={t('plugins.form.repositoryUrlHelper')}
                    leftIcon={<LinkIcon />}
                    error={errors.repositoryUrl?.message}
                    {...register('repositoryUrl')}
                  />
                </div>

                <div>
                  <Input
                    label={t('plugins.form.homepageUrl')}
                    placeholder="https://myplugin.com"
                    helperText={t('plugins.form.homepageUrlHelper')}
                    leftIcon={<LinkIcon />}
                    error={errors.homepageUrl?.message}
                    {...register('homepageUrl')}
                  />
                </div>

                <div className="md:col-span-2">
                  <Input
                    label={t('plugins.form.documentationUrl')}
                    placeholder="https://docs.myplugin.com"
                    helperText={t('plugins.form.documentationUrlHelper')}
                    leftIcon={<LinkIcon />}
                    error={errors.documentationUrl?.message}
                    {...register('documentationUrl')}
                  />
                </div>
              </div>
            </Card.Content>
          </Card>

          {/* Tags and Keywords */}
          <Card className="p-6">
            <Card.Header>
              <Card.Title>{t('plugins.form.tagsKeywords')}</Card.Title>
              <Card.Description>
                {t('plugins.form.tagsKeywordsDescription')}
              </Card.Description>
            </Card.Header>
            <Card.Content>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Input
                    label={t('plugins.form.keywords')}
                    placeholder={t('plugins.form.keywordsPlaceholder')}
                    helperText={t('plugins.form.keywordsHelper')}
                    leftIcon={<TagIcon />}
                    error={errors.keywords?.message}
                    {...register('keywords')}
                  />
                </div>

                <div>
                  <Input
                    label={t('plugins.form.tags')}
                    placeholder={t('plugins.form.tagsPlaceholder')}
                    helperText={t('plugins.form.tagsHelper')}
                    leftIcon={<TagIcon />}
                    error={errors.tags?.message}
                    {...register('tags')}
                  />
                </div>
              </div>
            </Card.Content>
          </Card>

          {/* Submit Actions */}
          <Card className="p-6">
            <div className="flex justify-end space-x-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => navigate('/developer/plugins')}
                disabled={isSubmitting}
              >
                {t('common.cancel')}
              </Button>
              <Button
                type="submit"
                loading={isSubmitting}
                disabled={isSubmitting}
              >
                {t('plugins.createNew')}
              </Button>
            </div>
          </Card>
        </form>
      </div>
    </ErrorBoundary>
  )
}
